//
//  CarFriendViewController.m
//  LoveCar
//
//  Created by Xue Senhong on 15/5/21.
//  Copyright (c) 2015年 薛森鸿. All rights reserved.
//

#import "CarFriendViewController.h"
#import "CarFriendCell.h"
#import "CarFriendModel.h"
#import "MJRefresh.h"
#import "MJRefreshHeaderView.h"
#import "MJRefreshFooterView.h"
#import "CarFriendNewViewController.h"
#import "UMSocial.h"
#import "CarFriendImg.h"
#import "MyCollectionview.h"

@interface CarFriendViewController ()<UITableViewDelegate, UITableViewDataSource, UICollectionViewDataSource, UICollectionViewDelegate , UICollectionViewDelegateFlowLayout, UIScrollViewDelegate,ToCarFriendDelegate>

@property (nonatomic, retain) UITableView *table;
@property (nonatomic, retain) UITableView *sTable;
@property (nonatomic, retain) NSMutableArray *sArray;
@property (nonatomic, retain) NSMutableArray *array;
@property (nonatomic, retain) UIButton *a;
@property (nonatomic, retain) UIButton *b;


@end

@implementation CarFriendViewController
- (void)dealloc
{
    [_table release];
    [_sTable release];
    [_sArray release];
    [_array release];
    [_a release];
    [_b release];
    [_sendArray release];
    [_myCollect release];
    [_myScroll release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.array = [NSMutableArray array];
    self.sArray = [NSMutableArray array];
    self.sendArray = [NSArray array];
    self.pageCount = 120404;
    [self step];
    [self createCollectionView];
    [self createTable];
    [self setupRefresh];
}
// 设置
- (void)step
{
    self.navigationItem.title = @"推荐";
    self.navigationController.navigationBar.translucent = NO;
    self.tabBarController.tabBar.translucent = NO;
    
    UIView *title = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
    [self.navigationItem setTitleView:title];
    [title release];
    
    self.a = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 70, 30)];
    [_a setTitle:@"推荐" forState:UIControlStateNormal];
    [_a setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [_a addTarget:self action:@selector(oldAction) forControlEvents:UIControlEventTouchUpInside];
    [title addSubview:_a];
    [_a release];
    
    self.b = [[UIButton alloc] initWithFrame:CGRectMake(80, 0, 70, 30)];
    [_b setTitle:@"最新" forState:UIControlStateNormal];
    [_b setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    _b.titleLabel.font = [UIFont systemFontOfSize:14];
    [_b addTarget:self action:@selector(newAction) forControlEvents:UIControlEventTouchUpInside];
    [title addSubview:_b];
    [_b release];
    
}

- (void)oldAction
{
    self.myCollect.contentOffset = CGPointMake(0, 0);
    [_a setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    _a.titleLabel.font = [UIFont systemFontOfSize:17];
    [_b setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    _b.titleLabel.font = [UIFont systemFontOfSize:14];
}
- (void)newAction
{
    self.myCollect.contentOffset = CGPointMake(self.view.frame.size.width, 0);
    [_a setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    _a.titleLabel.font = [UIFont systemFontOfSize:14];
    [_b setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    _b.titleLabel.font = [UIFont systemFontOfSize:17];
}

// 更新cell
- (void)reloadDataForCell
{
    NSString *str = @"http://api.ycapp.yiche.com/appforum/cheyouhome/";
    AFHTTPRequestOperationManager *m = [AFHTTPRequestOperationManager manager];
    m.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    __block CarFriendViewController *carFriendViewController = self;
    [m GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:   NSJSONReadingMutableContainers error:nil];
        [carFriendViewController.array addObjectsFromArray:[dic objectForKey:@"data"]];
        [carFriendViewController.table reloadData];
        [carFriendViewController.table headerEndRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    NSString *mstr = @"http://api.ycapp.yiche.com/appforum/cheyouhome/?isall=1&deviceid=868033012409837";
    AFHTTPRequestOperationManager *mm = [AFHTTPRequestOperationManager manager];
    mm.responseSerializer = [AFHTTPResponseSerializer serializer];
    [mm GET:mstr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:   NSJSONReadingMutableContainers error:nil];
        [carFriendViewController.sArray addObjectsFromArray:[dic objectForKey:@"data"]];
        [carFriendViewController.sTable reloadData];
        [carFriendViewController.sTable headerEndRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}
/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.table addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.sTable addHeaderWithTarget:self action:@selector(headerRereshing)];
    //#warning 自动刷新(一进入程序就下拉刷新)
    [self.table headerBeginRefreshing];
    [self.sTable headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.table addFooterWithTarget:self action:@selector(footerRereshing)];
    [self.sTable addFooterWithTarget:self action:@selector(footerRereshing)];
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{

    [self reloadDataForCell];
    
}

- (void)footerRereshing
{
    NSString *str = [NSString stringWithFormat:@"http://api.ycapp.yiche.com/appforum/cheyouhome/?minid=%ld&deviceid=868033012409837", self.pageCount];
    AFHTTPRequestOperationManager *m = [AFHTTPRequestOperationManager manager];
    m.responseSerializer = [AFHTTPResponseSerializer serializer];
    __block CarFriendViewController *carFriendViewController = self;
    [m GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:   NSJSONReadingMutableContainers error:nil];
        //self.array = [dic objectForKey:@"data"];
        [carFriendViewController.array addObjectsFromArray:[dic objectForKey:@"data"]];
        carFriendViewController.pageCount -= 100;
        [carFriendViewController.table reloadData];
        [carFriendViewController.table footerEndRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    NSString *mstr = [NSString stringWithFormat:@"http://api.ycapp.yiche.com/appforum/cheyouhome/?minid=%ld&isall=1&deviceid=868033012409837", self.pageCount];
    AFHTTPRequestOperationManager *mm = [AFHTTPRequestOperationManager manager];
    mm.responseSerializer = [AFHTTPResponseSerializer serializer];
    [mm GET:mstr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:   NSJSONReadingMutableContainers error:nil];
        //self.array = [dic objectForKey:@"data"];
        [carFriendViewController.sArray addObjectsFromArray:[dic objectForKey:@"data"]];
        carFriendViewController.pageCount -= 100;
        [carFriendViewController.sTable reloadData];
        [carFriendViewController.sTable footerEndRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}
- (void)createCollectionView
{
    
    UICollectionViewFlowLayout *myLayout = [[UICollectionViewFlowLayout alloc] init];
    myLayout.minimumLineSpacing = 0;
    myLayout.minimumInteritemSpacing = 0; // 列间距
    myLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.myCollect = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64 - 49) collectionViewLayout:myLayout];
    self.myCollect.delegate = self;
    self.myCollect.dataSource = self;
    self.myCollect.pagingEnabled = YES;
    self.myCollect.showsHorizontalScrollIndicator = NO;
    self.myCollect.contentSize = CGSizeMake(self.view.frame.size.width * 2, self.view.frame.size.height);
    self.myCollect.showsHorizontalScrollIndicator = NO;
    [self.myCollect registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"ccell"];
    self.myCollect.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_myCollect];
    [_myCollect release];
    [myLayout release];
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (self.myCollect.contentOffset.x == self.view.frame.size.width) {
        [_a setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        _a.titleLabel.font = [UIFont systemFontOfSize:14];
        [_b setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        _b.titleLabel.font = [UIFont systemFontOfSize:17];
    }
    if (self.myCollect.contentOffset.x == 0) {
        [_a setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        _a.titleLabel.font = [UIFont systemFontOfSize:17];
        [_b setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        _b.titleLabel.font = [UIFont systemFontOfSize:14];
    }
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(self.view.frame.size.width, self.view.frame.size.height);
}
// 创建table
- (void)createTable
{
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64 - 49) style:UITableViewStylePlain];
    _table.rowHeight = 700;
    _table.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    _table.dataSource = self;
    _table.delegate = self;
    UINib *nib = [UINib nibWithNibName:@"CarFriendCell" bundle:[NSBundle mainBundle]];
    [_table registerNib:nib forCellReuseIdentifier:@"cell"];
    [_table release];
    
    self.sTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64 - 49) style:UITableViewStylePlain];
    _sTable.rowHeight = 700;
    _sTable.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    _sTable.dataSource = self;
    _sTable.delegate = self;
    UINib *nnib = [UINib nibWithNibName:@"CarFriendCell" bundle:[NSBundle mainBundle]];
    [_sTable registerNib:nnib forCellReuseIdentifier:@"cell"];
    [_sTable release];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSDictionary *dic = [NSDictionary dictionary];
    if (tableView == _table) {
        dic = [self.array objectAtIndex:indexPath.row];
    }
    if (tableView == _sTable) {
        dic = [self.sArray objectAtIndex:indexPath.row];
    }
    NSDictionary *f = @{NSFontAttributeName:[UIFont systemFontOfSize:17]};
    CGRect rect = [[dic objectForKey:@"context"] boundingRectWithSize:CGSizeMake(260, 90) options:NSStringDrawingUsesLineFragmentOrigin attributes:f context:nil];
    NSArray *imgList = [dic objectForKey:@"imageList"];
    CGFloat imgHeight = (imgList.count + 2) / 3 * 85;
    if (tableView == self.table) {
        return 55 + rect.size.height + imgHeight + 250;
    } else if (tableView == self.sTable) {
        return 55 + rect.size.height + imgHeight + 230;
    }
    return 55 + rect.size.height + imgHeight + 230;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _table) {
        return self.array.count;
    } else {
        return self.sArray.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _table) {
        CarFriendCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        cell.delegate = self;
        NSDictionary *dic = [self.array objectAtIndex:indexPath.row];
        self.sendArray = [dic objectForKey:@"imageList"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell sampleCellWithDic:dic];
        
        return cell;
    } else {
        CarFriendCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        NSDictionary *dic = [self.sArray objectAtIndex:indexPath.row];
        cell.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell sampleCellWithDic:dic];

        return cell;
    }
    
}

- (void)toCarFriend:(NSArray *)array index:(NSInteger)page
{
     CarFriendImg *imgCell = [[CarFriendImg alloc] init];
    imgCell.getArray = array;
    imgCell.page = page;
    [imgCell setModalTransitionStyle:2];
    [self presentViewController:imgCell animated:YES completion:nil];
    [imgCell release];
}


#pragma mark collection协议
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 2;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ccell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    if (indexPath.row == 0) {
        [cell addSubview:self.table];
    }
    if (indexPath.row == 1) {
        [cell addSubview:self.sTable];
    }
    return cell;
    
    return nil;
}


@end
